<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Produit_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    public function getList() {
        return $this->db
                        ->select('produit.ARTICLE_ID, ARTICLE_REF, ARTICLE_LIBELLE')
                        ->from('article')
                        ->join('produit', 'article.ARTICLE_ID = produit.ARTICLE_ID')
                        ->get()
                        ->result();
    }

    public function get($ARTICLE_ID) {
        $result = $this->db
                ->select('article.ARTICLE_ID, ARTICLE_REF, ARTICLE_LIBELLE')
                ->from('article')
                ->join('produit', 'article.ARTICLE_ID = produit.ARTICLE_ID')
                ->where('ARTICLE_ID', $ARTICLE_ID)
                ->get()
                ->result();

        if (count($result) == 1) {
            $result = $result[0];
        }

        return $result;
    }

    public function getAlerts() {
        $articles = $this->db
                ->select('ARTICLE_ID, ARTICLE_REF, ARTICLE_LIBELLE, ARTICLE_SEUIL')
                ->from('ARTICLE')
                ->where('ARTICLE_MATIERE_PREMIERE', false)
                ->get()
                ->result()
        ;

        foreach ($articles as $key => $art) {
            $articles[$key]->ARTICLE_SEUIL = (int) $articles[$key]->ARTICLE_SEUIL;
            $stock = $this->db
                    ->select('SUM(STOCK_QUANTITE) as STOCK')
                    ->from('STOCK')
                    ->where('ARTICLE_ID', $art->ARTICLE_ID)
                    ->get()
                    ->result();
            if (count($stock) > 0) {
                if ($stock[0]->STOCK == null)
                    $articles[$key]->STOCK = 0;
                else
                    $articles[$key]->STOCK = (int) $stock[0]->STOCK;
            }
            else
                $articles[$key]->STOCK = 0;

            if ($articles[$key]->STOCK >= $articles[$key]->ARTICLE_SEUIL)
                unset($articles[$key]);
        }

        return $articles;
    }

}

?>